package fnic.prehand.common;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;

import org.apache.log4j.Logger;

public class BlockQueueService {
	private static AgentConfig config = AgentConfig.getInstance();
	private static Logger LOG = Logger.getLogger(BlockQueueService.class);
	private static int BULKSIZE = config.getclientBulkSize();
	private LinkedBlockingQueue<String> inQueue;
	/**
	 * singleton access
	 */
//	private static BlockQueueService instance = new BlockQueueService();
//
//	public static BlockQueueService getInstance() {
//		return instance;
//	}

	public BlockQueueService(){
		inQueue = new LinkedBlockingQueue<String>();
	}
	// **
	// 探针推送的测试结果，待ES入索引
	// *
	

	public String getInQueueItem() {
		String item = null;
		try {
			item = inQueue.take();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			LOG.error("inQueue interrupt, " + e.getMessage());
		}
		return item;
	}

	/*
	 * 从阻塞队列inQueue中获取数据， 超过BULKSIZE即刻返回，否则耗时0.5s，
	 */
	public List<String> getInQueueItems() {
		int i = 0;
		ArrayList<String> alist = new ArrayList<String>();
		try {
			while (i < BULKSIZE) {
				String tmp = inQueue.poll(500, TimeUnit.MILLISECONDS);
				if (tmp == null) {
					break;
				}
				alist.add(tmp);
			}
		} catch (InterruptedException e) {
			LOG.error("block queue interrupt, " + e.getMessage());
		}
//		System.out.println("queue size:"+alist.size()+", contents:"+alist.toString());
		return alist;
	}

	// 向inQueue中添加数据，队列不限大小，暂时没有用阻塞方法
	public void addInQueueItem(String item) {
		inQueue.add(item);
	}
}
